//
//  SelectPicker.m
//  OA-JZD
//
//  Created by apple on 2018/1/31.
//  Copyright © 2018年 JC. All rights reserved.
//

#import "SelectPicker.h"

#define SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)
#define SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)
#define BACKGROUND_BLACK_COLOR [UIColor colorWithRed:0.412 green:0.412 blue:0.412 alpha:0.7]
static const NSInteger SelectPickerViewDefaultHeight = 248;
static const NSInteger SelectToolBarHeight = 44;
@implementation SelectPickerComponentObject
- (instancetype)init{
    return [self initWithText:@"" subArray:[NSMutableArray array]];
}

- (instancetype)initWithText:(NSString *)text{
    return [self initWithText:text subArray:[NSMutableArray array]];
}


- (instancetype)initWithText:(NSString *)text subArray:(NSMutableArray *)array{
    if (self = [super init]) {
        _text = text;
        _subArray = array;
    }
    return self;
}

@end

@implementation SelectPickerBuilder

- (instancetype)init{
    if (self = [super init]) {
        _showMask = YES;
        _defaultIndex = 0;
        _pickerHeight = SelectPickerViewDefaultHeight;
    }
    return self;
}

-(void)setDefaultIndex:(NSInteger)defaultIndex
{
    _defaultIndex =defaultIndex;
}
@end



@interface SelectPicker()<UIPickerViewDelegate,UIPickerViewDataSource>
@property (nonatomic, assign, getter=isLinkage) BOOL linkage;
@property (nonatomic, assign) NSInteger numberOfComponents;
@property (nonatomic, strong) SelectPickerBuilder *builder;
@property (nonatomic, copy) NSArray<SelectPickerComponentObject *> *componets;
@property (nonatomic, copy) SelectPickerConfirmBlock confirmBlock;
@property (nonatomic, copy) SelectPickerCancelBlock cancelBlock;
@property (nonatomic, copy) NSArray<NSArray <NSString*> *> *stringArrays;
@property (nonatomic, strong) NSMutableArray<NSMutableArray <SelectPickerComponentObject *> *> *rows;
@property (nonatomic, strong) UIPickerView *pickerView;
@property (nonatomic, strong) UIButton *confirmButton;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *cancelButton;
@property (nonatomic, strong) UIView *containerView;

@end
@implementation SelectPicker


#pragma mark - setup

- (void)config{
    if (!self.isLinkage) {
        self.numberOfComponents = self.stringArrays.count;
    }
    else{
        self.rows = [NSMutableArray array];
        SelectPickerComponentObject *object = self.componets.firstObject;
        [self.rows setObject:[NSMutableArray arrayWithArray:self.componets] atIndexedSubscript:0];
        for (self.numberOfComponents = 1;; self.numberOfComponents++) {
            [self.rows setObject:object.subArray atIndexedSubscript:self.numberOfComponents];
            object = [self objectAtIndex:0 inObject:object];
            if (!object) {
                break;
            }
        }
    }
    [self setupViews];
}

+ (void)showSinglePickerInView:(UIView *)view
withBuilder:(SelectPickerBuilder *)builder
strings:(NSArray<NSString *> *)strings
confirm:(SelectPickerConfirmBlock)confirmBlock
cancel:(SelectPickerCancelBlock)cancelBlcok{
//    CGRect frame =CGRectMake(0, 0, view.width, view.height-64);
//    SelectPicker *pickerView = [[SelectPicker alloc]initWithFrame:view.frame];
    
    SelectPicker *pickerView = [[SelectPicker alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    
    NSMutableArray *tmp = [NSMutableArray arrayWithCapacity:strings.count];
    for (NSString *string in strings) {
        SelectPickerComponentObject *object = [[SelectPickerComponentObject alloc]initWithText:string];
        [tmp addObject:object];
    }
    pickerView.linkage = YES;
    pickerView.componets = [tmp copy];
    pickerView.stringArrays = [tmp copy];
    pickerView.confirmBlock = confirmBlock;
    pickerView.cancelBlock = cancelBlcok;
    pickerView.builder = builder ?:[SelectPickerBuilder new];
    [pickerView config];
    [view addSubview:pickerView];
}

+ (void)showMultiPickerInView:(UIView *)view
withBuilder:(SelectPickerBuilder *)builder
stringArrays:(NSArray<NSArray<NSString *> *> *)arrays
confirm:(SelectPickerConfirmBlock)confirmBlock cancel:(SelectPickerCancelBlock)cancelBlcok{
//    SelectPicker *pickerView = [[SelectPicker alloc]initWithFrame:view.frame];
    SelectPicker *pickerView = [[SelectPicker alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    
    pickerView.linkage = NO;
    pickerView.stringArrays = arrays;
    pickerView.confirmBlock = confirmBlock;
    pickerView.cancelBlock = cancelBlcok;
    pickerView.builder = builder ?:[SelectPickerBuilder new];
    [pickerView config];
    [view addSubview:pickerView];
}


+ (void)showLinkagePickerInView:(UIView *)view
withBuilder:(SelectPickerBuilder *)builder
components:(NSArray<SelectPickerComponentObject *> *)components
confirm:(SelectPickerConfirmBlock)confirmBlock
cancel:(SelectPickerCancelBlock)cancelBlcok{
//    SelectPicker *pickerView = [[SelectPicker alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    SelectPicker *pickerView = [[SelectPicker alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    
    pickerView.linkage = YES;
    pickerView.componets = components;
    pickerView.confirmBlock = confirmBlock;
    pickerView.cancelBlock = cancelBlcok;
    pickerView.builder = builder ?:[SelectPickerBuilder new];
    [pickerView config];
     
    [view addSubview:pickerView];
}

//省市区选择控件
+ (void)showAddressPickerInView:(UIView *)view
                    withBuilder:(nullable SelectPickerBuilder *)builder
                        confirm:(SelectPickerConfirmBlock)confirmBlock
                         cancel:(SelectPickerCancelBlock)cancelBlcok{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Province&City&District.plist" ofType:nil];
    NSDictionary *dict = [NSDictionary  dictionaryWithContentsOfFile:path];
    NSMutableArray *provinceArr = [[NSMutableArray alloc]init];
    for(int i =0;i<34;i++){
        NSString *idkey = [NSString stringWithFormat:@"%d",i];
        NSDictionary *dict1 = dict[idkey];
        NSString *province = dict1[@"name"];//山东省
        //省
        SelectPickerComponentObject *provinceComObject = [[SelectPickerComponentObject alloc]initWithText:province];
        //市
        NSMutableArray *cityArr = [[NSMutableArray alloc]init];
        NSArray *arr1 = [dict1 objectForKey:province];//各市
        for (NSDictionary *dic in arr1) {
            NSString *city = dic[@"name"];
            NSArray *arr2 = [dic objectForKey:city];
            SelectPickerComponentObject *cityComObject = [[SelectPickerComponentObject alloc]initWithText:city];
            [cityArr addObject:cityComObject];
            //区
            NSMutableArray *areaArr = [[NSMutableArray alloc]init];
            for (NSDictionary *dic in arr2) {
                NSString *area = dic[@"name"];
                SelectPickerComponentObject *areaComObject = [[SelectPickerComponentObject alloc]initWithText:area];
                [areaArr addObject:areaComObject];
            }
            cityComObject.subArray =areaArr;
        }
        provinceComObject.subArray =cityArr;
        [provinceArr addObject:provinceComObject];
    }
    NSArray * arr= [provinceArr copy];
//    SelectPicker *pickerView = [[SelectPicker alloc]initWithFrame:view.frame];
    SelectPicker *pickerView = [[SelectPicker alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-statsBarHeight-44)];
    
    pickerView.linkage = YES;
    pickerView.componets = [arr copy] ;//components;
    pickerView.confirmBlock = confirmBlock;
    pickerView.cancelBlock = cancelBlcok;
    pickerView.builder = builder ?:[SelectPickerBuilder new];
    [pickerView config];
    
    [view addSubview:pickerView];
}





- (void)setupViews{
    self.backgroundColor = self.builder.isShowMask ? BACKGROUND_BLACK_COLOR : UIColor.clearColor;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dissView)];
    [self addGestureRecognizer:tap];
    [self addSubview:self.containerView];
    
    [self.containerView addSubview:self.pickerView];
    [self.containerView addSubview:self.titleLabel];
    [self.containerView addSubview:self.confirmButton];
    [self.containerView addSubview:self.cancelButton];
    
}


#pragma mark - event response

- (void)confirm:(UIButton *)button{
    if (self.confirmBlock){
        NSMutableArray<NSString *> *resultStrings = [NSMutableArray arrayWithCapacity:self.numberOfComponents];
        NSMutableArray<NSNumber *> *resultIndexs = [NSMutableArray arrayWithCapacity:self.numberOfComponents];
        if ([self configResultStrings:resultStrings indexs:resultIndexs]) {
            self.confirmBlock([resultStrings copy],[resultIndexs copy]);
        }
    }
    [self removeFromSuperview];
}

- (void)dissView{
    if (self.cancelBlock) {
        self.cancelBlock();
    }
    [self removeFromSuperview];
}

- (void)cancel:(UIButton *)button{
    [self dissView];
}


#pragma mark - private

- (BOOL)configResultStrings:(NSMutableArray <NSString *> *)strings indexs:(NSMutableArray <NSNumber *> *)indexs{
    if (!strings || !indexs) {
        return NO;
    }
    
    [strings removeAllObjects];
    [indexs removeAllObjects];
    
    if (!self.isLinkage) {
        for (NSInteger index = 0; index < self.numberOfComponents; index++) {
            NSInteger indexRow = [self.pickerView selectedRowInComponent:index];
            [indexs addObject:@(indexRow)];
            NSArray<NSString *> *tmp = self.stringArrays[index];
            if (tmp.count > 0) {
                [strings addObject:tmp[indexRow]];
            }
        }
    }
    else{
        for (NSInteger index = 0; index < self.numberOfComponents; index++) {
            NSInteger indexRow = [self.pickerView selectedRowInComponent:index];
            [indexs addObject:@(indexRow)];
            NSMutableArray<SelectPickerComponentObject *> *tmp = self.rows[index];
            if (tmp.count > 0) {
                [strings addObject:tmp[indexRow].text];
            }
        }
    }
    return YES;
}

- (SelectPickerComponentObject *)objectAtIndex:(NSInteger)index inObject:(SelectPickerComponentObject *)object{
    if (object.subArray.count > index) {
        return object.subArray[index];
    }
    return nil;
}


#pragma mark - PickerDataSource

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return self.numberOfComponents;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if (!self.isLinkage) {
        return self.stringArrays[component].count;
    }
    else{
        return self.rows[component].count;
    }
}



#pragma mark - PickerDelegate
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
    return 40;
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    if (!self.isLinkage) {
        return;
    }
    
    if (component < (self.numberOfComponents - 1)) {
        NSMutableArray<SelectPickerComponentObject *> *tmp = self.rows[component];
        if (tmp.count > 0) {
            tmp = tmp[row].subArray;
        }
        [self.rows setObject:((tmp.count > 0) ? tmp : [NSMutableArray array])  atIndexedSubscript:component + 1];
        
        [self pickerView:pickerView didSelectRow:0 inComponent:component + 1];
        [pickerView selectRow:0 inComponent:component + 1 animated:NO];
    }
    [pickerView reloadComponent:component];
}


- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    //设置分割线的颜色
    for(UIView *singleLine in pickerView.subviews){
        if (singleLine.frame.size.height < 1){
            //            singleLine.backgroundColor = UIColor.clearColor;
        }
    }
    //设置文字的属性
    UILabel *genderLabel = [UILabel new];
    genderLabel.textAlignment = NSTextAlignmentCenter;
    genderLabel.font = [UIFont systemFontOfSize:16.0];
    genderLabel.textColor = self.builder.pickerTextColor ?: UIColor.blackColor;
    
    if (!self.isLinkage) {
        NSArray<NSString *> *tmp = self.stringArrays[component];
        if (tmp.count > 0) {
            genderLabel.text = tmp[row];
        }
    }
    else{
        NSArray<SelectPickerComponentObject *> *tmp = self.rows[component];
        if (tmp.count > 0) {
            genderLabel.text = tmp[row].text;
        }
    }
    return genderLabel;
}



#pragma mark - getter

- (UIView *)containerView{
    if (!_containerView) {
        NSLog(@"containerView   self.builder.pickerHeight==%f",self.builder.pickerHeight);
        CGFloat pickerViewHeight = self.builder.pickerHeight > SelectToolBarHeight ? self.builder.pickerHeight : SelectPickerViewDefaultHeight;
//        _containerView = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT - pickerViewHeight, SCREEN_WIDTH, pickerViewHeight)];
        _containerView = [[UIView alloc]initWithFrame:CGRectMake(0, self.frame.size.height - pickerViewHeight, SCREEN_WIDTH, pickerViewHeight)];
        _containerView.backgroundColor = self.builder.pickerColor ?: UIColor.whiteColor;
        UIView *topview = [[UIView alloc]initWithFrame:CGRectMake(0,  0, SCREEN_WIDTH, 40)];
        topview.backgroundColor= RGBCOLOR(247, 247, 247);
        [_containerView addSubview:topview];
        
    }
    return _containerView;
}



- (UIButton *)confirmButton{
    if (!_confirmButton) {
        _confirmButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH -50, 5, 40, 30)];
        _confirmButton.backgroundColor = UIColor.clearColor;
        _confirmButton.titleLabel.font = [UIFont systemFontOfSize:15.0];
        NSString *title = self.builder.confirmText.length ? self.builder.confirmText : @"确定";
        [_confirmButton setTitle:title forState:UIControlStateNormal];
        UIColor *color = self.builder.confirmTextColor ?: TITLECOLOR;//;
        [_confirmButton setTitleColor:color forState:UIControlStateNormal];
        [_confirmButton addTarget:self action:@selector(confirm:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _confirmButton;
}

- (UILabel *)titleLabel{
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 5, SJScreenW, 30)];
//        _titleLabel.backgroundColor = [UIColor greenColor];//UIColor.clearColor;
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.font = [UIFont systemFontOfSize:18.0];
        _titleLabel.text = self.builder.titleText.length ? self.builder.titleText : @""; 
    }
    return _titleLabel;
}


- (UIButton *)cancelButton{
    if (!_cancelButton) {
        _cancelButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 5, 40, 30)];
        _cancelButton.backgroundColor = UIColor.clearColor;
        _cancelButton.titleLabel.font = [UIFont systemFontOfSize:15.0];
        NSString *title = self.builder.cancelText.length ? self.builder.cancelText : @"取消";
        [_cancelButton setTitle:title forState:UIControlStateNormal];
        UIColor *color = self.builder.cancelTextColor ?: TITLECOLOR;//;
        [_cancelButton setTitleColor:color forState:UIControlStateNormal];
        [_cancelButton addTarget:self action:@selector(cancel:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancelButton;
}


- (UIPickerView *)pickerView{
    if (!_pickerView) {
        NSLog(@"self.builder.pickerHeight==%f",self.builder.pickerHeight);
        NSLog(@"SelectToolBarHeight==%ld",(long)SelectToolBarHeight);
        CGFloat pickerViewHeight = _containerView.frame.size.height;//self.builder.pickerHeight > SelectToolBarHeight ? self.builder.pickerHeight : SelectPickerViewDefaultHeight;
//        _pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0,SelectToolBarHeight, SCREEN_WIDTH, pickerViewHeight - SelectToolBarHeight)];
         _pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0,SelectToolBarHeight, SCREEN_WIDTH, pickerViewHeight - SelectToolBarHeight)];
        _pickerView.backgroundColor =  UIColor.clearColor;
        _pickerView.delegate = self;
        _pickerView.dataSource = self;
        NSLog(@"self.builder.defaultIndex==%ld",(long)self.builder.defaultIndex);
        NSLog(@"self.numberOfComponents==%ld",(long)self.numberOfComponents);
        if (self.builder.defaultIndex >0  && self.builder.defaultIndex <= self.componets.count ) {
            [_pickerView selectRow:self.builder.defaultIndex inComponent:0 animated:NO];
        }else{
            [_pickerView selectRow:0 inComponent:0 animated:NO];
        }
//        NSInteger defaultIndex =  (self.builder.defaultIndex < self.numberOfComponents && self.builder.defaultIndex > 0) ? self.builder.defaultIndex : 0;
//        NSLog(@"%ld--z",(long)defaultIndex);
//        [_pickerView selectRow:defaultIndex inComponent:0 animated:NO];
    }
    return _pickerView;
}

@end

